from flask import Blueprint,jsonify, request
from main.OCR.AipOcr import *
from main.utils import InterfaceHelper,RequestHelper
import  urllib.parse
ocr = Blueprint('ocr',__name__)
from main import basedir
from main.utils import FileHelper, JSONHelper
import time, os

@ocr.route('/ocr/', methods=["POST"])
def ocr_ask():
    res = {}
    dict = RequestHelper.formToDict(request)
    print(dict)
    f = request.files['file']
    if f:
        print("文件传输")
    if f:  # 判断是否是允许上传的文件类型
        print(f.filename)
        ext = f.filename.rsplit('.', 1)[1]  # 获取文件后缀
        unix_time = int(time.time())
        new_filename = str(unix_time) + '.' + ext
        f.save(os.path.join(basedir, "static", "images", new_filename))  # 保存文件到upload目录
        print(new_filename)

    res = get_ocr_result(os.path.join(basedir, "static", "images", new_filename))
    var = ""
    for item in res:
        var = var + " "+item['words']
    res={"result": var}

    if dict:
        res['state'] = 1
        res['msg'] = "上传成功"
    else:
        res['state'] = 0
        res['msg'] = "上传失败"

    return jsonify(res)
    # dic = RequestHelper.formToDict(request)
    # print(type(dic['image_url']))
    # res = get_ocr_result(urllib.parse.quote(dic['image_url']))
    # var=""
    # for item in res:
    #     var=var+" "+item['words']
    # res={"result":var}
    #
    # return jsonify(res)

